package com.graduation.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduation.springbootinit.service.ClothingProductService;
import com.graduation.springbootinit.mapper.ClothingProductMapper;
import com.graduation.springbootinit.mapper.SizeStockMapper;
import com.graduation.springbootinit.model.entity.ShopPart.ClothingProduct;
import com.graduation.springbootinit.model.entity.ShopPart.SizeStock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;

@Service
public class ClothingProductServiceImpl extends ServiceImpl<ClothingProductMapper, ClothingProduct>
        implements ClothingProductService {

    @Resource
    private SizeStockMapper sizeStockMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProduct(ClothingProduct product) {
        // 1. 保存商品基本信息
        if (product.getStatus() == null) {
            product.setStatus(1);  // 默认上架
        }
        if (product.getSalesCount() == null) {
            product.setSalesCount(0);  // 默认销量为0
        }
        
        // 保存商品基本信息，MyBatis-Plus会自动将生成的ID设置到product对象中
        boolean saved = save(product);
        
        // 2. 保存尺码库存信息
        if (product.getSizeStocks() != null && !product.getSizeStocks().isEmpty()) {
            for (SizeStock sizeStock : product.getSizeStocks()) {
                // 使用已经生成的商品ID
                sizeStock.setProductId(product.getId());
                sizeStockMapper.insert(sizeStock);
            }
        }
        
        return product.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(ClothingProduct product) {
        // 1. 更新商品基本信息
        updateById(product);
        
        // 2. 更新尺码库存信息
        if (product.getSizeStocks() != null) {
            // 先删除原有的尺码库存
            QueryWrapper<SizeStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("product_id", product.getId());
            sizeStockMapper.delete(queryWrapper);
            
            // 保存新的尺码库存
            for (SizeStock sizeStock : product.getSizeStocks()) {
                sizeStock.setProductId(product.getId());
                sizeStockMapper.insert(sizeStock);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProduct(Long id) {
        // 1. 删除尺码库存
        QueryWrapper<SizeStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", id);
        sizeStockMapper.delete(queryWrapper);
        
        // 2. 删除商品
        removeById(id);
    }

    @Override
    public ClothingProduct getProductById(Long id) {
        // 1. 获取商品基本信息
        ClothingProduct product = getById(id);
        if (product != null) {
            // 2. 获取尺码库存信息
            List<SizeStock> sizeStocks = sizeStockMapper.listByProductId(id);
            product.setSizeStocks(sizeStocks);
        }
        return product;
    }

    @Override
    public Page<ClothingProduct> listProducts(Page<ClothingProduct> page, String keyword, Integer categoryId,
            String sortField, String sortOrder, BigDecimal minPrice, BigDecimal maxPrice) {
        // 1. 构建查询条件
        QueryWrapper<ClothingProduct> queryWrapper = new QueryWrapper<>();
        
        // 关键词搜索（商品名称或描述）
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like("name", keyword)
                    .or()
                    .like("description", keyword));
        }
        
        // 分类过滤
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        
        // 价格区间过滤
        if (minPrice != null || maxPrice != null) {
            if (minPrice != null) {
                queryWrapper.ge("price", minPrice);
            }
            if (maxPrice != null) {
                queryWrapper.le("price", maxPrice);
            }
            // 价格区间查询时默认按价格升序排序
            queryWrapper.orderByAsc("price");
        } else {
            // 没有价格区间时，按照其他排序规则
            if (StringUtils.isNotBlank(sortField)) {
                boolean isAsc = "asc".equalsIgnoreCase(sortOrder);
                switch (sortField) {
                    case "price":
                        queryWrapper.orderBy(true, isAsc, "price");
                        break;
                    case "sales":
                        queryWrapper.orderBy(true, isAsc, "sales_count");
                        break;
                    default:
                        queryWrapper.orderByAsc("id");
                }
            } else {
                // 默认按ID升序排序
                queryWrapper.orderByAsc("id");
            }
        }
        
        // 2. 执行分页查询
        Page<ClothingProduct> productPage = page(page, queryWrapper);
        
        // 3. 查询每个商品的尺码库存
        for (ClothingProduct product : productPage.getRecords()) {
            List<SizeStock> sizeStocks = sizeStockMapper.listByProductId(product.getId());
            product.setSizeStocks(sizeStocks);
        }
        
        return productPage;
    }

    @Override
    public ClothingProduct getById(Serializable id) {
        // 1. 获取商品基本信息
        QueryWrapper<ClothingProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ClothingProduct product = getOne(queryWrapper);

        // 2. 如果商品存在，查询尺码库存
        if (product != null) {
            QueryWrapper<SizeStock> stockWrapper = new QueryWrapper<>();
            stockWrapper.eq("product_id", id);
            List<SizeStock> sizeStocks = sizeStockMapper.selectList(stockWrapper);
            product.setSizeStocks(sizeStocks);
        }

        return product;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSizeStock(Long productId, List<SizeStock> sizeStocks) {
        // 先删除原有的尺码库存
        QueryWrapper<SizeStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        sizeStockMapper.delete(queryWrapper);
        
        // 保存新的尺码库存
        if (sizeStocks != null && !sizeStocks.isEmpty()) {
            sizeStocks.forEach(stock -> {
                stock.setProductId(productId);
                sizeStockMapper.insert(stock);
            });
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean increaseStock(Long productId, String size, Integer quantity) {
        QueryWrapper<SizeStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId)
                   .eq("size", size);
                   
        SizeStock sizeStock = sizeStockMapper.selectOne(queryWrapper);
        if (sizeStock == null) {
            // 如果不存在该尺码的库存记录，创建一个新的
            sizeStock = new SizeStock();
            sizeStock.setProductId(productId);
            sizeStock.setSize(size);
            sizeStock.setStock(quantity);
            return sizeStockMapper.insert(sizeStock) > 0;
        } else {
            // 更新库存
            sizeStock.setStock(sizeStock.getStock() + quantity);
            return sizeStockMapper.updateById(sizeStock) > 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean decreaseStock(Long productId, String size, Integer quantity) {
        QueryWrapper<SizeStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId)
                   .eq("size", size);
                   
        SizeStock sizeStock = sizeStockMapper.selectOne(queryWrapper);
        if (sizeStock == null || sizeStock.getStock() < quantity) {
            // 如果不存在该尺码的库存记录或库存不足
            return false;
        }

        // 更新库存
        sizeStock.setStock(sizeStock.getStock() - quantity);
        return sizeStockMapper.updateById(sizeStock) > 0;
    }


    @Override
    public List<ClothingProduct> getProductsByStoreId(Long storeId) {
        // 1. 构建查询条件
        QueryWrapper<ClothingProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        
        // 2. 查询该店铺的所有商品
        List<ClothingProduct> products = list(queryWrapper);
        
        // 3. 查询每个商品的尺码库存信息
        for (ClothingProduct product : products) {
            List<SizeStock> sizeStocks = sizeStockMapper.listByProductId(product.getId());
            product.setSizeStocks(sizeStocks);
        }
        
        return products;
    }

    @Override
    public Page<ClothingProduct> listStoreProducts(Page<ClothingProduct> page, Long storeId) {
        // 1. 构建查询条件
        QueryWrapper<ClothingProduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        
        // 默认按ID升序排序
        queryWrapper.orderByAsc("id");
        
        // 2. 执行分页查询
        Page<ClothingProduct> productPage = page(page, queryWrapper);
        
        // 3. 查询每个商品的尺码库存
        for (ClothingProduct product : productPage.getRecords()) {
            List<SizeStock> sizeStocks = sizeStockMapper.listByProductId(product.getId());
            product.setSizeStocks(sizeStocks);
        }
        
        return productPage;
    }
} 